// pages/addFamily/addFamily.js
var app = getApp()
import util from "../../utils/util.js"
import http from "../../utils/http.js"
let scrollWeightTimer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 0, // 0 添加 1编辑
    userId: 0, // 0 或不传代表自己，否则代表其他人
    nickname: "",
    switchChecked: false,
    islogin:false,
    isagree: false,
    sexShow: false,
    sex:'0',
    sexFormatted: "男",
    birthdayShow:false,
    birthday: '',
    weightShow: false,
    targetNum: "",
    sexs:[{
      text: '男',
      value: 0
    },{
      text: '女',
      value: 1
    }],
    maxDate: new Date().getTime(),
    minDate: new Date("1900-01-01").getTime(),
    defultDate: new Date("1990-03-11").getTime(),
    formatter(type, value) {
      if (type === 'year') {  
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return `${value}日`;
    },
    drinkNum: 0,
    weight: "",// 最终选中的体重
    weightValue: '50.0', // 测量尺的默认体重值
    weightNum: 2000 + 42 * app.globalData.screenScale, //测量尺刻度的数量
    scrollLeft: 4550,
    intoId: 'id1000',
    cupList:[{
      deviceCode: ""
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      type: options.type,
      islogin: options.islogin,
      userId: options.userId ? options.userId : 0
    })
    if(this.data.type == 1) {
      this.getUserInfo()
    }
    let title = ""
    console.log("------"+this.data.islogin);
    if(this.data.islogin=="true") {
      title = "设置本人饮水信息"
    }else{
      if(this.data.type == 1) { // 编辑
        title =  '编辑家人饮水信息'
      }else{
        title = '设置家人饮水信息'
      }
    }
    wx.setNavigationBarTitle({
      title
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },
  switchChange(e){
    const value = e.detail

  },
  checkChange(e) {
    console.log(e)
  },
  openSexShow(){
    this.setData({ sexShow: true });
  },
  sexConfirm(e) {
    console.log(e.detail.value.value)
    this.setData({ 
      sexShow: false,
      sex: e.detail.value.value,
      sexFormatted: e.detail.value.text
    });
  },
  onClose() {
    this.setData({ 
      sexShow: false,
      birthdayShow: false,
      weightShow:false
    });
  },
  openBirthdayShow(e){
    this.setData({
      birthdayShow: true
    })
  },
  openWeightyShow(e){
    this.setData({
      weightShow: true,
    })
    setTimeout(() => {
      this.setData({
        scrollLeft: this.data.scrollLeft
      })
    }, 100);
    // wx.nextTick(() => {
    //   this.setData({
    //     scrollLeft: 4550
    //   })
    // })
  },
  dateConfirm(e){
    let date = e.detail
    this.setData({
      birthday: util.formatDate(new Date(date)),
      birthdayShow: false
    })
  },
  dateCancel(){
    this.setData({
      birthdayShow: false
    })
  },
  getUserInfo(){
    let params = {}
    if(this.data.userId != 0){
      params.userId = this.data.userId
    }
    http.request("/drinkUsers/getUserInfo",params)
    .then(res=>{
      // 初始化体重
      let scale = 1 //app.globalData.screenScale
      let scrollLeft = 0
      let unit = (18 / 2) * scale
      let unit10 = (unit * 10 + 1) // 每10个小格子的长度
      let weightValue = res.data.weight
      let ruleValue = weightValue * 10
      scrollLeft = parseInt(ruleValue / 10) * unit10 + ruleValue % 10 * unit + 1
      // 时间戳
      let defultDate = res.data.birthday * 1000  

      this.setData({
        nickname: res.data.nickname,
        sex: res.data.sex,
        sexFormatted: res.data.sexFormatted,
        birthday: res.data.birthdayFormatted,
        weight: res.data.weight,
        drinkNum: res.data.recommendWaterQuantity,
        targetNum: res.data.waterQuantityPlan,
        cupList: res.data.cups,
        weightValue,
        scrollLeft,
        defultDate
      })

    })
    .catch(res=>{

    })
  },
  scrollChange(e) {
    let scale = 1 //app.globalData.screenScale
    let scrollLeft = e.detail.scrollLeft
    let unit = (18 / 2) * scale
    let unit10 = (unit * 10 + 1) // 每10个小格子的长度
    let weightValue1 = parseInt(scrollLeft / unit10) // 整数位
    let weightValue2 = parseInt(scrollLeft % unit10 - 1) / unit // 小数位
    // console.log("weightValue1",weightValue1)
    // console.log("weightValue2",weightValue2)
    let weightValue = (weightValue1 + weightValue2 / 10).toFixed(1)
    weightValue = weightValue > 0 ? weightValue : 0
    this.setData({
      weightValue: weightValue
    })
    // 200 毫秒后修正
    if (scrollWeightTimer) {
      clearTimeout(scrollWeightTimer)
    }
    // 修正真实的刻度
    let ruleValue = weightValue * 10
    scrollLeft = parseInt(ruleValue / 10) * unit10 + ruleValue % 10 * unit + 1

    scrollWeightTimer = setTimeout(() => {
      this.setData({
        scrollLeft
      })
    }, 200);
  },
  weightChange(){
    this.setData({
      weight: this.data.weightValue,
      weightShow: false,
      drinkNum: 40 * this.data.weightValue
    })
  },
  submit(){
    if(this.data.sex === '') {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
      return
    }
    if(this.data.birthday === '') {
      wx.showToast({
        title: '请选择出生日期',
        icon: 'none'
      })
      return
    }
    let params = {
      id: this.data.userId,
      name: this.data.nickname,
      sex: this.data.sex,
      birthday: this.data.birthday ?  new Date(this.data.birthday).getTime() / 1000 : 0, // 时间戳
      weight: this.data.weight,
      waterQuantity: this.data.drinkNum,
      waterQuantityPlan: this.data.targetNum,
      isWaterWarning: this.data.switchChecked ? 0 : 1
    }
    http.request("/drinkUsers/add", params)
    .then(res=>{
      app.globalData.isfirstMember = false
      wx.showToast({
        title: '操作成功',
        icon: "none"
      })
      wx.navigateTo({
        url: '/pages/drinkerInfo/drinkerInfo',
      })
    })
    .catch(res=>{

    })
  },
  scan(e){
    let index = e.currentTarget.dataset.idx
    wx.scanCode({
      success:(res)=> {
        this.setData({
          [`cupList[${index}].deviceCode`]:  res.result
        })
      }
    })
  },
  nicknameChange(e){
    let nickname = e.detail.value
    this.setData({
      nickname
    })
  },
  targetNumChange(e){
    let targetNum = e.detail.value
    this.setData({
      targetNum
    })
  },
  agree(){
    this.setData({
      isagree: !this.data.isagree
    })
  },
  addCup(){
    let cupList = this.data.cupList
    cupList.push({
      deviceCode: ""
    })
    this.setData({
      cupList
    })
  },
  delCup(e){
    let cupList = this.data.cupList
    let index = e.currentTarget.dataset.index
    cupList.splice(index,1)
    this.setData({
      cupList
    })
  },
  cupChange(e){
    let index = e.currentTarget.dataset.index
    let value = e.detail.value
    this.setData({
      [`cupList[${index}].deviceCode`]: value
    })
  }
})